<template>
  <main>
    <div class="title">
      <h1>项 目 管 理</h1>
      <el-button
        class="createBtn"
        type="primary"
        size="mini"
        @click="handleCreate"
      >
        创建新项目
      </el-button>

      <el-dialog title="新项目" :visible.sync="dialogCreateVisible">
        <el-form :model="form">
          <el-form-item label="项目名称">
            <el-input
              v-model="form.name"
              autocomplete="off"
              ref="createInput"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelCreateProject">取 消</el-button>
          <el-button type="primary" @click="confirmCreateProject">
            确 定
          </el-button>
        </div>
      </el-dialog>
    </div>

    <el-table
      :data="getFilteredData"
      style="width: 100%"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="项目名称" prop="name"></el-table-column>
      <el-table-column label="修改时间" prop="updateTime"></el-table-column>
      <el-table-column align="center">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入关键字搜索"
            @change="handleChange(scope)"
          />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          &nbsp;
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>

          <el-dialog title="删除项目" :visible.sync="dialogDeleteVisible">
            <span
              >确定删除项目 <b>{{ selectedItem.name }} </b>吗？</span
            >
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogDeleteVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirmDeleteProject">
                确 定
              </el-button>
            </div>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>
  </main>
</template>

<script>
import axios from "axios";
import Cookies from "js-cookie";
// import uniqueId from "./uuid";
import { v4 as uuidV4 } from "uuid";

export default {
  data() {
    return {
      tableData: [],
      search: "",

      dialogCreateVisible: false,
      form: {
        name: "",
      },

      dialogDeleteVisible: false,
      selectedItem: {},
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    getFilteredData() {
      return this.tableData.filter(
        (data) =>
          !this.search ||
          data.name.toLowerCase().includes(this.search.toLowerCase())
      );
    },
  },
  methods: {
    init() {
      this.getProjectData();
    },
    getProjectData() {
      axios
        .get("/api/getUserProjects", {
          params: {
            userId: Cookies.get("userId"),
          },
        })
        .then((res) => {
          this.tableData = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleChange() {
      return;
    },
    handleEdit(row) {
      this.$router.push({ name: "Model", params: { id: row.id } });
    },
    handleDelete(row) {
      this.selectedItem = row;
      this.dialogDeleteVisible = true;
    },
    confirmDeleteProject() {
      axios
        .post("/api/deleteProject", {
          projectId: this.selectedItem.id,
        })
        .then((res) => {
          this.$message({
            message: res.data.message,
            type: "success",
          });
          this.getProjectData();
        })
        .catch((err) => {
          console.log(err);

          this.$message({
            message: "删除失败!",
            type: "error",
          });
        });

      this.dialogDeleteVisible = false;
    },

    handleCreate() {
      this.dialogCreateVisible = true;

      this.$nextTick(() => {
        this.$refs.createInput.focus();
      });
    },

    dateFormatFn(date, format = "YYYY-MM-DD HH:mm:ss") {
      let config = {
        YYYY: date.getFullYear(),
        MM:
          date.getMonth() + 1 > 10
            ? date.getMonth() + 1
            : "0" + (date.getMonth() + 1),
        DD: date.getDate() > 10 ? date.getDate() : "0" + date.getDate(),
        HH: date.getHours() > 10 ? date.getHours() : "0" + date.getHours(),
        mm:
          date.getMinutes() > 10 ? date.getMinutes() : "0" + date.getMinutes(),
        ss:
          date.getSeconds() > 10 ? date.getSeconds() : "0" + date.getSeconds(),
      };
      for (const key in config) {
        format = format.replace(key, config[key]);
      }
      return format;
    },

    cancelCreateProject() {
      this.dialogCreateVisible = false;
      this.form.name = "";
    },
    confirmCreateProject() {
      let uuid = uuidV4();
      let currentTime = this.dateFormatFn(new Date());
      const project = {
        id: uuid,
        name: this.form.name,
        createTime: currentTime,
        updateTime: currentTime,
        authorId: Cookies.get("userId"),
        projectData: [],
      };

      axios
        .post("/api/createProject", project)
        .then((res) => {
          this.$message({
            message: res.data.message,
            type: "success",
          });
          this.getProjectData();
        })
        .catch((err) => {
          console.log(err);
          this.$message({
            message: "新建失败！",
            type: "error",
          });
        });

      this.dialogCreateVisible = false;
      this.form.name = "";
    },
  },
};
</script>

<style lang="less" scoped>
main {
  width: 100%;
  margin: 0 4px;
  box-sizing: border-box;

  .title {
    position: relative;

    display: flex;

    h1 {
      text-align: center;
      flex-grow: 1;
    }

    .createBtn {
      position: absolute;
      right: 50px;
      top: 25%;
    }
  }
}
</style>
